<?php


namespace App\Repository;


use App\Models\Admin\Permissions;

class PermissionsRepository
{
    public static $permissions;

    public function __construct(Permissions $permissions)
    {
        self::$permissions = $permissions;
    }

    /**
     * 获取菜单列表
     * @param $fields
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     * @author:
     * @date: 2019/5/23 11:43
     */
    public function getPermissions($fields,$where = [])
    {
        return self::$permissions::query()->select($fields)->where($where)->get();
    }

    /**
     * 添加菜单
     * @param $data
     * @return bool
     * @author:
     * @date: 2019/5/29 17:17
     */
    public function add($data)
    {
        return self::$permissions::query()->insert($data);
    }

    /**
     * 查找菜单
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function get($id)
    {
        return self::$permissions::query()->find($id);
    }

    /**
     * 查询子集
     * @param $pid
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function children($pid)
    {
        return self::$permissions::query()->where('pid',$pid)->get();
    }
    /**
     * 保存修改菜单
     * @param $data
     * @return bool
     */
    public function save($data)
    {
        $param = self::$permissions::query()->find($data['id']);
        foreach ($data as $key=>$val){
            $param->$key = $val;
        }
        return $param->save();
    }

    /**
     * 删除菜单
     * @param $id
     * @return mixed
     */
    public function delete($id)
    {
        return self::$permissions::query()->where('id',$id)->delete();
    }

    /**
     * 查询用户拥有的权限列表
     * @param $ids
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     * @author:
     * @date: 2019/5/30 11:31
     */
    public function userHasPermissions($ids)
    {
        return self::$permissions::query()
            ->whereIn('id',$ids)
            ->where('is_show',1)
            ->select(['id','name','icon','pid','routes','alias','module','controller','action'])
            ->get();
    }

}